package com.insigma.business.qrcode.common._provider.impl;

import com.insigma.business.qrcode.common.converter.SystemConfigProviderConverter;
import com.insigma.business.qrcode.common.dto.BaseLogRequest;
import com.insigma.business.qrcode.common.dto.SystemConfigDTO;
import com.insigma.business.qrcode.common.service.GovOrgService;
import com.insigma.business.qrcode.common._provider.SystemConfigProvider;
import com.insigma.business.qrcode.common.service.ZzdService;
import com.insigma.business.qrcode.common.util.AdminAreaCodeUtils;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.LogUtil;
import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.soldier.dto.ContactNoDTO;
import com.insigma.business.qrcode.soldier.dto.SimpleApiRequest;
import com.insigma.business.qrcode.soldier.dto.SystemConfigService;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.soldier.entity.GovOrgDO;
import com.insigma.business.qrcode.soldier.entity.SystemConfigDO;
import com.insigma.business.qrcode.soldier.request.BaseGetRequest;
import com.insigma.business.qrcode.soldier.request.SystemConfigUpdateRequest;
import com.insigma.business.qrcode.soldier.util.OkHttp3Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.insigma.business.qrcode.common.dto.ContactNoBO;
import com.insigma.business.qrcode.common.util.CommonConstant;


import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
@Component("systemConfigProvider")
public class SystemConfigProviderImpl extends BaseProviderImpl implements SystemConfigProvider {

    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private GovOrgService govOrgService;

    @Autowired
    @Lazy
    private ZzdService zzdService;


    @Override
    public BaseResponse<List<SystemConfigDTO>> listAllSystemConfig() {


        final BaseResponse<List<SystemConfigDTO>> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
            }

            @Override
            public void executeService() {
                final List<SystemConfigDO> systemConfigDOList = systemConfigService.list();
                final List<SystemConfigDTO> systemConfigDTOList = SystemConfigProviderConverter.convertResponseDOList2DTOList(systemConfigDOList);
                ResponseUtils.setupSuccessResponse(baseResponse, systemConfigDTOList);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SYSTEM_CONFIG_LIST;
            }
        });

        return baseResponse;
    }


    @Override
    public BaseResponse<SystemConfigDTO> getSystemConfig(final BaseGetRequest baseGetRequest) {

        final BaseResponse<SystemConfigDTO> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(baseGetRequest, "获取单条SystemConfig的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) baseGetRequest.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                final SystemConfigDO systemConfigDO = systemConfigService.get((Long) baseGetRequest.getId());
                final SystemConfigDTO remoteObj = SystemConfigProviderConverter.convertResponseDO2DTO(systemConfigDO);
                ResponseUtils.setupSuccessResponse(baseResponse, remoteObj);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SYSTEM_CONFIG_GET;
            }
        });

        return baseResponse;
    }


    @Override
    public BaseResponse<SystemConfigDTO> getSystemConfigByName(final String name) {


        final BaseResponse<SystemConfigDTO> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotBlank(name, "配置项名称不能为空");
            }

            @Override
            public void executeService() {
                final SystemConfigDO systemConfigDO = systemConfigService.getByName(name);
                final SystemConfigDTO remoteObj = SystemConfigProviderConverter.convertResponseDO2DTO(systemConfigDO);
                ResponseUtils.setupSuccessResponse(baseResponse, remoteObj);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SYSTEM_CONFIG_GET_BY_NAME;
            }
        });

        return baseResponse;
    }


    @Override
    public BaseResponse<Integer> updateSystemConfig(final SystemConfigUpdateRequest updateRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(updateRequest, "修改SystemConfig的请求参数不能为空");
                BizCheckUtil.checkNotNull(updateRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotNull(updateRequest.getModifierId(), "操作人不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierType(), "操作人类型不能为空");
            }

            @Override
            public void executeService() {
                SystemConfigDO systemConfigDO = SystemConfigProviderConverter.convertRequestUO2DO(updateRequest);
                Integer affectRowNum = systemConfigService.update(systemConfigDO);
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SYSTEM_CONFIG_UPDATE;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<Boolean> sendSmsCode(String phoneNumber, String code) {
        Boolean b = zzdService.sendSmsCode(phoneNumber, code);
        return ResponseUtils.buildSuccessResponse(b);
    }

    @Override
    public BaseResponse<Boolean> sendSmsCodeByShipingtai(String phoneNumber, String code) {
        logger.info("send message, phone:{}, code:{}", phoneNumber, code);
        String xmlTemplate = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:DefaultNamespace\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <urn:STRUSERID>EC371E815AC295A548258137002B3C18</urn:STRUSERID>\n" +
                "      <urn:STRPWD>password</urn:STRPWD>\n" +
                "      <urn:STRSENDTO>%s</urn:STRSENDTO>\n" +
                "      <urn:STRSMSCONTENT>您的验证码为：%S</urn:STRSMSCONTENT>\n" +
                "      <urn:STRSENDER>【退役局】</urn:STRSENDER>\n" +
                "      <urn:STRRESPONSEPHONE></urn:STRRESPONSEPHONE>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        String xml = String.format(xmlTemplate, phoneNumber, code);
        String uri = "http://172.18.18.17:80/esoa/webservice/fileservice.nsf/smsservice?OpenWebService";
        String s = OkHttp3Util.sendXml(uri, xml);
        logger.info(s);
        return ResponseUtils.buildSuccessResponse(true);
    }

    @Override
    public BaseResponse<ContactNoDTO> getContactNo(String areaCode) {

        ContactNoBO cachedContactNo = systemConfigService.getCachedContactNo(areaCode);

        ContactNoDTO dto = new ContactNoDTO();
        BeanUtils.copyProperties(cachedContactNo, dto);

        SystemConfigDTO tec = getSystemConfigByName(CommonConstant.TECHNICAL_SUPPORT).getDto();
        if (tec != null) {
            dto.setTechnicalSupportNo(tec.getValue());
        }

        return ResponseUtils.buildSuccessResponse(dto);
    }

    @Override
    public BaseResponse<ContactNoDTO> queryCommonContactNo(SimpleApiRequest request) {

        String adminCode = request.getAdminAreaCode();

        ContactNoDTO dto = new ContactNoDTO();
        dto.setAdminAreaCode(adminCode);
        String shiAdminCode = AdminAreaCodeUtils.fillAreaCode(AdminAreaCodeUtils.getCutAdminAreaCode(adminCode, 2));
        String quAdminCode = AdminAreaCodeUtils.fillAreaCode(AdminAreaCodeUtils.getCutAdminAreaCode(adminCode, 3));
        String key = CommonConstant.PREFIX_DISTRICT_CONTACT_NO + shiAdminCode;
        SystemConfigDO configDo = systemConfigService.getByName(key);
        if (configDo != null) {
            dto.setCityContactNo(configDo.getValue());
        }

        String quKey = CommonConstant.PREFIX_DISTRICT_CONTACT_NO + quAdminCode;
        SystemConfigDO quConfigDo = systemConfigService.getByName(quKey);
        if (quConfigDo != null) {
            dto.setCountyContactNo(quConfigDo.getValue());
        }

        SystemConfigDO telNo = systemConfigService.getByName(CommonConstant.TECHNICAL_SUPPORT);
        if (telNo != null) {
            dto.setTechnicalSupportNo(telNo.getValue());
        }

        int level = AdminAreaCodeUtils.getLevel(adminCode);
        if (level >= 4) {
            String zhenAdminCode = AdminAreaCodeUtils.fillAreaCode(AdminAreaCodeUtils.getCutAdminAreaCode(adminCode, 4));
            GovOrgDO byAreaCodeAndId = govOrgService.getByAreaCodeAndId(zhenAdminCode, null);
            if (byAreaCodeAndId != null) {
                dto.setTownContactNo(byAreaCodeAndId.getContactNum());
            }
        }

        if (level >= 5) {
            String zhenAdminCode = AdminAreaCodeUtils.fillAreaCode(AdminAreaCodeUtils.getCutAdminAreaCode(adminCode, 5));
            GovOrgDO byAreaCodeAndId = govOrgService.getByAreaCodeAndId(zhenAdminCode, null);
            if (byAreaCodeAndId != null) {
                dto.setVillageContactNo(byAreaCodeAndId.getContactNum());
            }
        }
        return ResponseUtils.buildSuccessResponse(dto);
    }


    @Override
    public void saveLog(final BaseLogRequest insertRequest) {
        LogUtil.info(log, "插入日志，请求参数:", insertRequest);


        BizCheckUtil.checkNotNull(insertRequest, "新增的请求参数不能为空");
        BizCheckUtil.checkNotBlank(insertRequest.getActionId(), "新增actionId参数不能为空");
        BizCheckUtil.checkNotBlank(insertRequest.getAppCode(), "新增AppCode参数不能为空");
        BizCheckUtil.checkNotBlank(insertRequest.getAreaCode(), "新增actionId参数不能为空");
        BizCheckUtil.checkNotNull(insertRequest.getActionType(), "新增actionId参数不能为空");
        BizCheckUtil.checkNotBlank(insertRequest.getUserRole(), "新增UserRole参数不能为空");
        BizCheckUtil.checkNotBlank(insertRequest.getActionId(), "新增ActionId参数不能为空");

        insertRequest.setActionTime(LocalDateTime.now());
        systemConfigService.insertLog(insertRequest);

    }

}
